// AdminRegisterDialog.java - 全新的管理员注册对话框
package com.library.gui;

import com.library.service.AuthService;
import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

public class AdminRegisterDialog extends JDialog {
    private AuthService authService;
    private JTextField usernameField;
    private JPasswordField passwordField;
    private JPasswordField confirmPasswordField;
    private JTextField emailField;
    private JTextField adminIdField;
    private JTextField realNameField;
    private JTextField phoneField;
    private JComboBox<String> departmentCombo;
    private JComboBox<String> positionCombo;

    public AdminRegisterDialog(JFrame parent, AuthService authService) {
        super(parent, "管理员账户注册", true);
        this.authService = authService;
        initializeUI();
    }

    private void initializeUI() {
        setSize(500, 600);
        setLocationRelativeTo(getParent());
        setResizable(false);

        JPanel mainPanel = new JPanel(new BorderLayout(10, 10));
        mainPanel.setBorder(BorderFactory.createEmptyBorder(15, 15, 15, 15));

        // 创建标题
        JLabel titleLabel = new JLabel("管理员账户注册", JLabel.CENTER);
        titleLabel.setFont(new Font("微软雅黑", Font.BOLD, 20));
        titleLabel.setForeground(new Color(103, 58, 183)); // 深紫色主题
        titleLabel.setBorder(BorderFactory.createEmptyBorder(0, 0, 10, 0));
        mainPanel.add(titleLabel, BorderLayout.NORTH);

        // 创建选项卡面板
        JTabbedPane tabbedPane = new JTabbedPane();
        tabbedPane.addTab("账户信息", createAccountInfoPanel());
        tabbedPane.addTab("管理员信息", createAdminInfoPanel());

        mainPanel.add(tabbedPane, BorderLayout.CENTER);

        // 按钮面板
        JPanel buttonPanel = createButtonPanel();
        mainPanel.add(buttonPanel, BorderLayout.SOUTH);

        add(mainPanel);
    }

    private JPanel createAccountInfoPanel() {
        JPanel panel = new JPanel(new GridBagLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(25, 25, 25, 25));
        panel.setBackground(Color.WHITE);

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(8, 8, 8, 8);

        // 用户名
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.weightx = 0.4;
        panel.add(createRequiredLabel("用户名*:"), gbc);

        gbc.gridx = 1;
        gbc.weightx = 0.6;
        usernameField = new JTextField();
        usernameField.setToolTipText("用于登录系统的用户名");
        panel.add(usernameField, gbc);

        // 密码
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.weightx = 0.4;
        panel.add(createRequiredLabel("密码*:"), gbc);

        gbc.gridx = 1;
        gbc.weightx = 0.6;
        passwordField = new JPasswordField();
        passwordField.setToolTipText("密码长度至少8位，建议包含字母和数字");
        panel.add(passwordField, gbc);

        // 确认密码
        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.weightx = 0.4;
        panel.add(createRequiredLabel("确认密码*:"), gbc);

        gbc.gridx = 1;
        gbc.weightx = 0.6;
        confirmPasswordField = new JPasswordField();
        panel.add(confirmPasswordField, gbc);

        // 邮箱
        gbc.gridx = 0;
        gbc.gridy = 3;
        gbc.weightx = 0.4;
        panel.add(createRequiredLabel("邮箱*:"), gbc);

        gbc.gridx = 1;
        gbc.weightx = 0.6;
        emailField = new JTextField();
        emailField.setToolTipText("用于接收系统通知和重置密码");
        panel.add(emailField, gbc);

        // 提示信息
        gbc.gridx = 0;
        gbc.gridy = 4;
        gbc.gridwidth = 2;
        gbc.weightx = 1.0;
        JPanel hintPanel = new JPanel(new BorderLayout());
        hintPanel.setBackground(new Color(255, 243, 224));
        hintPanel.setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createLineBorder(new Color(255, 167, 38)),
            BorderFactory.createEmptyBorder(8, 8, 8, 8)
        ));
        JLabel hintLabel = new JLabel("<html><font color='#E65100' size='2'>" +
            "<b>安全提示：</b><br>" +
            "• 管理员账户具有系统最高权限<br>" +
            "• 请使用强密码并定期更换<br>" +
            "• 妥善保管账户信息</font></html>");
        hintPanel.add(hintLabel, BorderLayout.CENTER);
        panel.add(hintPanel, gbc);

        return panel;
    }

    private JPanel createAdminInfoPanel() {
        JPanel panel = new JPanel(new GridBagLayout());
        panel.setBorder(BorderFactory.createEmptyBorder(25, 25, 25, 25));
        panel.setBackground(Color.WHITE);

        GridBagConstraints gbc = new GridBagConstraints();
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.insets = new Insets(8, 8, 8, 8);

        // 管理员ID
        gbc.gridx = 0;
        gbc.gridy = 0;
        gbc.weightx = 0.4;
        panel.add(createRequiredLabel("管理员ID*:"), gbc);

        gbc.gridx = 1;
        gbc.weightx = 0.6;
        adminIdField = new JTextField();
        adminIdField.setToolTipText("唯一的管理员标识号");
        panel.add(adminIdField, gbc);

        // 真实姓名
        gbc.gridx = 0;
        gbc.gridy = 1;
        gbc.weightx = 0.4;
        panel.add(createRequiredLabel("真实姓名*:"), gbc);

        gbc.gridx = 1;
        gbc.weightx = 0.6;
        realNameField = new JTextField();
        panel.add(realNameField, gbc);

        // 电话
        gbc.gridx = 0;
        gbc.gridy = 2;
        gbc.weightx = 0.4;
        panel.add(createRequiredLabel("联系电话*:"), gbc);

        gbc.gridx = 1;
        gbc.weightx = 0.6;
        phoneField = new JTextField();
        panel.add(phoneField, gbc);

        // 所属部门
        gbc.gridx = 0;
        gbc.gridy = 3;
        gbc.weightx = 0.4;
        panel.add(new JLabel("所属部门:"), gbc);

        gbc.gridx = 1;
        gbc.weightx = 0.6;
        departmentCombo = new JComboBox<>(new String[]{
            "系统管理部", "图书采编部", "流通服务部", "信息技术部", "读者服务部", "综合办公室"
        });
        panel.add(departmentCombo, gbc);

        // 职位
        gbc.gridx = 0;
        gbc.gridy = 4;
        gbc.weightx = 0.4;
        panel.add(new JLabel("职位:"), gbc);

        gbc.gridx = 1;
        gbc.weightx = 0.6;
        positionCombo = new JComboBox<>(new String[]{
            "系统管理员", "图书管理员", "流通管理员", "技术支持", "服务专员", "部门主管"
        });
        panel.add(positionCombo, gbc);

        // 权限说明
        gbc.gridx = 0;
        gbc.gridy = 5;
        gbc.gridwidth = 2;
        gbc.weightx = 1.0;
        JPanel permissionPanel = new JPanel(new BorderLayout());
        permissionPanel.setBackground(new Color(232, 245, 233));
        permissionPanel.setBorder(BorderFactory.createCompoundBorder(
            BorderFactory.createLineBorder(new Color(76, 175, 80)),
            BorderFactory.createEmptyBorder(8, 8, 8, 8)
        ));
        JLabel permissionLabel = new JLabel("<html><font color='#2E7D32' size='2'>" +
            "<b>管理员权限说明：</b><br>" +
            "• 管理图书信息和读者账户<br>" +
            "• 处理借阅和归还业务<br>" +
            "• 查看系统统计报表<br>" +
            "• 配置系统参数和规则</font></html>");
        permissionPanel.add(permissionLabel, BorderLayout.CENTER);
        panel.add(permissionPanel, gbc);

        return panel;
    }

    private JPanel createButtonPanel() {
        JPanel panel = new JPanel(new FlowLayout(FlowLayout.CENTER, 20, 10));
        panel.setBackground(Color.WHITE);
        panel.setBorder(BorderFactory.createEmptyBorder(10, 0, 0, 0));

        JButton registerButton = new JButton("注册管理员账户");
        registerButton.setBackground(new Color(103, 58, 183));
        registerButton.setForeground(Color.black);
        registerButton.setFont(new Font("微软雅黑", Font.BOLD, 14));
        registerButton.setPreferredSize(new Dimension(150, 40));
        registerButton.setFocusPainted(false);

        JButton cancelButton = new JButton("取消注册");
        cancelButton.setBackground(new Color(117, 117, 117));
        cancelButton.setForeground(Color.black);
        cancelButton.setFont(new Font("微软雅黑", Font.PLAIN, 14));
        cancelButton.setPreferredSize(new Dimension(100, 40));
        cancelButton.setFocusPainted(false);

        registerButton.addActionListener(new RegisterAction());
        cancelButton.addActionListener(e -> dispose());

        panel.add(registerButton);
        panel.add(cancelButton);

        return panel;
    }

    private JLabel createRequiredLabel(String text) {
        JLabel label = new JLabel(text);
        label.setFont(new Font("微软雅黑", Font.BOLD, 13));
        label.setForeground(new Color(103, 58, 183));
        return label;
    }

    private class RegisterAction implements ActionListener {
        @Override
        public void actionPerformed(ActionEvent e) {
            // 获取输入数据
            String username = usernameField.getText().trim();
            String password = new String(passwordField.getPassword());
            String confirmPassword = new String(confirmPasswordField.getPassword());
            String email = emailField.getText().trim();
            String adminId = adminIdField.getText().trim();
            String realName = realNameField.getText().trim();
            String phone = phoneField.getText().trim();
            String department = (String) departmentCombo.getSelectedItem();
            String position = (String) positionCombo.getSelectedItem();

            // 数据验证
            if (!validateInput(username, password, confirmPassword, email, adminId, realName, phone)) {
                return;
            }

            // 执行注册
            boolean success = authService.registerAdmin(username, password, email, adminId, realName, phone);

            if (success) {
                JOptionPane.showMessageDialog(AdminRegisterDialog.this, 
                    "<html><center>" +
                    "<b style='color: #2E7D32; font-size: 14px;'>管理员账户注册成功!</b><br><br>" +
                    "<table align='center' cellspacing='5'>" +
                    "<tr><td><b>用户名:</b></td><td>" + username + "</td></tr>" +
                    "<tr><td><b>真实姓名:</b></td><td>" + realName + "</td></tr>" +
                    "<tr><td><b>管理员ID:</b></td><td>" + adminId + "</td></tr>" +
                    "<tr><td><b>所属部门:</b></td><td>" + department + "</td></tr>" +
                    "</table><br>" +
                    "请使用新账户登录管理系统后台。" +
                    "</center></html>", 
                    "注册成功", JOptionPane.INFORMATION_MESSAGE);
                dispose();
            } else {
                JOptionPane.showMessageDialog(AdminRegisterDialog.this, 
                    "<html><center><b style='color: #C62828;'>注册失败!</b><br>" +
                    "可能的原因：<br>" +
                    "• 用户名已存在<br>" +
                    "• 管理员ID已被使用<br>" +
                    "• 系统错误，请重试</center></html>", 
                    "注册失败", JOptionPane.ERROR_MESSAGE);
            }
        }

        private boolean validateInput(String username, String password, String confirmPassword,
                                    String email, String adminId, String realName, String phone) {
            // 检查必填字段
            if (username.isEmpty() || password.isEmpty() || email.isEmpty() ||
                adminId.isEmpty() || realName.isEmpty() || phone.isEmpty()) {
                JOptionPane.showMessageDialog(AdminRegisterDialog.this, 
                    "<html><center><b style='color: #EF6C00;'>请填写所有必填字段!</b><br>" +
                    "带 * 号的字段为必填项</center></html>", 
                    "输入错误", JOptionPane.WARNING_MESSAGE);
                return false;
            }

            // 检查密码一致性
            if (!password.equals(confirmPassword)) {
                JOptionPane.showMessageDialog(AdminRegisterDialog.this, 
                    "两次输入的密码不一致!", "输入错误", JOptionPane.WARNING_MESSAGE);
                confirmPasswordField.setText("");
                confirmPasswordField.requestFocus();
                return false;
            }

            // 检查密码强度
            if (password.length() < 8) {
                JOptionPane.showMessageDialog(AdminRegisterDialog.this, 
                    "<html><center><b>密码强度不足!</b><br>" +
                    "管理员密码长度不能少于8位</center></html>", 
                    "输入错误", JOptionPane.WARNING_MESSAGE);
                passwordField.setText("");
                confirmPasswordField.setText("");
                passwordField.requestFocus();
                return false;
            }

            // 检查密码复杂性
            if (!password.matches(".*[A-Za-z].*") || !password.matches(".*\\d.*")) {
                JOptionPane.showMessageDialog(AdminRegisterDialog.this, 
                    "<html><center><b>密码复杂性不足!</b><br>" +
                    "管理员密码应包含字母和数字</center></html>", 
                    "输入错误", JOptionPane.WARNING_MESSAGE);
                passwordField.setText("");
                confirmPasswordField.setText("");
                passwordField.requestFocus();
                return false;
            }

            // 检查用户名是否存在
            if (authService.isUsernameExists(username)) {
                JOptionPane.showMessageDialog(AdminRegisterDialog.this, 
                    "用户名已存在，请选择其他用户名!", "注册失败", JOptionPane.ERROR_MESSAGE);
                usernameField.requestFocus();
                return false;
            }

            // 简单的邮箱格式验证
            if (!email.matches("^[A-Za-z0-9+_.-]+@(.+)$")) {
                JOptionPane.showMessageDialog(AdminRegisterDialog.this, 
                    "请输入有效的邮箱地址!", "输入错误", JOptionPane.WARNING_MESSAGE);
                emailField.requestFocus();
                return false;
            }

            // 电话格式验证
            if (!phone.matches("\\d{11}")) {
                JOptionPane.showMessageDialog(AdminRegisterDialog.this, 
                    "请输入11位手机号码!", "输入错误", JOptionPane.WARNING_MESSAGE);
                phoneField.requestFocus();
                return false;
            }

            // 管理员ID格式验证
            if (!adminId.matches("ADMIN\\d+")) {
                JOptionPane.showMessageDialog(AdminRegisterDialog.this, 
                    "<html><center><b>管理员ID格式错误!</b><br>" +
                    "正确格式：ADMIN+数字<br>" +
                    "例如：ADMIN001、ADMIN123</center></html>", 
                    "输入错误", JOptionPane.WARNING_MESSAGE);
                adminIdField.requestFocus();
                return false;
            }

            return true;
        }
    }
}